<template>
  <div class="student-activities">
    <div class="activities-header">
      <div class="title">
        <icon name="calendar-check" class="title-icon"></icon>
        <span>学生参与活动</span>
      </div>
    </div>

    <div class="activities-table">
      <div class="table-header">
        <div class="table-cell name-cell">姓名</div>
        <div class="table-cell group-cell">组别</div>
        <div class="table-cell class-cell">班级</div>
        <div class="table-cell activity-cell">活动名称</div>
        <div class="table-cell time-cell">活动时间</div>
      </div>

      <div class="table-body custom-scrollbar">
        <div v-if="loading" class="loading-overlay">
          <i class="el-icon-loading"></i>
          <p>正在加载数据...</p>
        </div>

        <div v-else-if="filteredActivities.length === 0" class="no-data">
          <p>没有找到符合条件的活动数据</p>
        </div>

        <div v-else class="table-content">
          <div
            v-for="(activity, index) in filteredActivities"
            :key="index"
            class="table-row"
          >
            <div class="table-cell name-cell">{{ activity.name }}</div>
            <div class="table-cell group-cell">{{ activity.groupName }}</div>
            <div class="table-cell class-cell">{{ activity.classes }}</div>
            <div class="table-cell activity-cell">{{ activity.activityName }}</div>
            <div class="table-cell time-cell">{{ formatDate(activity.activityTime) }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination">
      <button
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
        class="page-btn"
      >
        <i class="el-icon-arrow-left"></i>
      </button>
      <span class="page-info">
        第 <b>{{ currentPage }}</b> / <b>{{ totalPages }}</b> 页
      </span>
      <button
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
        class="page-btn"
      >
        <i class="el-icon-arrow-right"></i>
      </button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'StudentActivities',
  data() {
    return {
      loading: true,
      activities: [],
      currentPage: 1,
      itemsPerPage: 15,
      total: 0
    }
  },
  computed: {
    filteredActivities() {
      let filtered = this.activities;
      if (this.searchText) {
      const searchLower = this.searchText.toLowerCase();
        filtered = this.activities.filter(activity => {
        return activity.name.toLowerCase().includes(searchLower) ||
               activity.classes.toString().includes(searchLower) ||
               activity.groupName.toString().includes(searchLower) ||
               activity.activityName.toLowerCase().includes(searchLower);
      });
      }
      // 不再做 slice，直接返回
      return filtered;
    },
    totalPages() {
      return Math.ceil(this.total / this.itemsPerPage);
    }
  },
  mounted() {
    this.loadActivitiesData(1);
    this.$nextTick(() => {
      setTimeout(() => {
        this.startAutoScroll();
      }, 1000);
    });
  },
  beforeDestroy() {
    if (this.autoScrollInterval) {
      clearInterval(this.autoScrollInterval);
    }
  },
  methods: {
    async loadActivitiesData(page = 1) {
      this.loading = true;
      try {
        const res = await this.$overviewapi.getActivities({ pageNum: page, pageSize: this.itemsPerPage });
        if (res.code === '200') {
          this.activities = res.data.map(item => ({
            id: item.id || '',
            name: item.name || '',
            groupName: item.groupName || '',
            classes: item.classes || '',
            activityName: item.activityName || '',
            activityTime: item.activityDate || ''
          }));
          this.total = 15 * this.itemsPerPage; // 先写死
          this.currentPage = page;
        } else {
          this.$message.error(res.msg || '获取数据失败');
          this.activities = [];
        }
      } catch (error) {
        console.error('加载活动数据失败:', error);
        this.$message.error('加载活动数据失败，请检查API连接');
        this.activities = [];
      } finally {
        this.loading = false;
      }
    },
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.loadActivitiesData(page);
    },
    formatDate(dateStr) {
      if (!dateStr || dateStr.length !== 8) return dateStr;
      return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
    },
    startAutoScroll() {
      if (this.activities.length <= 5) {
        // Don't auto-scroll if there are too few items
        return;
      }

      // Get the table body element
      const tableBody = this.$el.querySelector('.table-body');
      if (!tableBody) return;

      this.autoScrollInterval = setInterval(() => {
        if (this.scrollPaused || !this.autoScrollEnabled || this.searchText) {
          return;
        }

        // Increment scroll position
        this.scrollPosition += this.scrollSpeed;

        // Apply the scroll
        tableBody.scrollTop = this.scrollPosition;

        // If we've reached the bottom, reset after a delay
        if (tableBody.scrollTop + tableBody.clientHeight >= tableBody.scrollHeight) {
          this.pauseAutoScroll();

          // Reset to top after a delay
          setTimeout(() => {
            this.scrollPosition = 0;
            tableBody.scrollTop = 0;

            // Resume scrolling after another delay
            setTimeout(() => {
              this.resumeAutoScroll();
            }, 2000);
          }, 1000);
        }
      }, 30); // Update every 30ms for smooth scrolling

      // Add mouse events to pause scrolling when user interacts
      tableBody.addEventListener('mouseenter', this.pauseAutoScroll);
      tableBody.addEventListener('mouseleave', this.resumeAutoScroll);
    },

    pauseAutoScroll() {
      this.scrollPaused = true;
    },

    resumeAutoScroll() {
      if (this.searchText) return; // Don't resume if search is active
      this.scrollPaused = false;
    },

    toggleAutoScroll() {
      this.autoScrollEnabled = !this.autoScrollEnabled;

      if (this.autoScrollEnabled) {
        // Reset scroll position when enabling
        this.scrollPosition = 0;
        const tableBody = this.$el.querySelector('.table-body');
        if (tableBody) {
          tableBody.scrollTop = 0;
        }
        this.scrollPaused = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.student-activities {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  color: #d3d6dd;

  .activities-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid rgba(104, 216, 254, 0.3);

    .title {
      display: flex;
      align-items: center;
      font-size: 18px;
      font-weight: bold;
      color: #68d8fe;

      .title-icon {
        margin-right: 10px;
        font-size: 20px;
      }
    }
  }

  .activities-table {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: rgba(19, 25, 47, 0.4);
    border-radius: 6px;
    border: 1px solid rgba(104, 216, 254, 0.3);
    overflow: hidden;
    max-height: calc(100% - 60px); /* Adjust for header height */

    .table-header {
      display: flex;
      background-color: rgba(104, 216, 254, 0.1);
      border-bottom: 2px solid rgba(104, 216, 254, 0.5);
      font-weight: bold;
      color: #68d8fe;
      padding: 12px 0;
      position: sticky;
      top: 0;
      z-index: 5;
    }

    .table-body {
      flex: 1;
      overflow-y: auto;
      position: relative;
      max-height: calc(100vh - 250px); /* Adjust based on your layout */

      .loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: rgba(19, 25, 47, 0.8);
        z-index: 10;

        i {
          font-size: 40px;
          color: #68d8fe;
          margin-bottom: 20px;
        }

        p {
          color: #d3d6dd;
          font-size: 16px;
        }
      }

      .no-data {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        color: #d3d6dd;
        font-size: 16px;
      }

      .table-content {
        width: 100%;
        height: 100%;
        overflow-y: auto;

        .table-row {
          display: flex;
          border-bottom: 1px solid rgba(104, 216, 254, 0.1);
          transition: background-color 0.3s;

          &:hover {
            background-color: rgba(104, 216, 254, 0.05);
          }

          &:last-child {
            border-bottom: none;
          }
        }
      }
    }

    .table-cell {
      padding: 12px 15px;
      display: flex;
      align-items: center;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .name-cell {
      width: 15%;
    }

    .group-cell {
      width: 15%;
    }

    .class-cell {
      width: 15%;
    }

    .activity-cell {
      width: 30%;
    }

    .time-cell {
      width: 25%;
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 12px;
    gap: 8px;
    background: transparent;
    border-radius: 6px;
    padding: 2px 8px;
    box-shadow: none;

    .page-btn {
      background: linear-gradient(90deg, #1e2746 0%, #223a5e 100%);
      border: none;
      color: #68d8fe;
      font-size: 14px;
      border-radius: 50%;
      width: 28px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background 0.2s, color 0.2s;
      cursor: pointer;
      box-shadow: none;

      &:hover:not(:disabled) {
        background: linear-gradient(90deg, #68d8fe 0%, #1e2746 100%);
        color: #fff;
      }
      &:disabled {
        color: #888;
        background: #222b44;
        cursor: not-allowed;
        opacity: 0.5;
      }
    }

    .page-info {
      color: #d3d6dd;
      font-size: 13px;
      font-weight: 500;
      b {
        color: #68d8fe;
        font-size: 14px;
        font-weight: bold;
        margin: 0 2px;
      }
    }
  }
}

/* 自定义滚动条样式 */
.custom-scrollbar {
  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(19, 25, 47, 0.5);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(104, 216, 254, 0.5);
    border-radius: 4px;
    border: 2px solid rgba(19, 25, 47, 0.5);
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: rgba(104, 216, 254, 0.7);
  }
}
</style>
